package com.ruoyi.web.controller.API;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.model.YuLiStudioLoginUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.mytools.AliyunSMS;
import com.ruoyi.common.mytools.R;
import com.ruoyi.common.mytools.Tools;
import com.ruoyi.common.mytools.jwtUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import java.time.Clock;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.time.Duration;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping("/api")
@Anonymous
public class ApiController extends BaseController {

    @Resource
    HttpServletRequest request;

    @Autowired
    private RedisTemplate redisTemplate;

    //默认头像
    private String defaultHeadimg="https://yulistudio.oss-cn-shenzhen.aliyuncs.com/images/bg/yllogo.png";

    /**
     * 小程序登录请求
     */
    @PostMapping("/login")
    public R login(@RequestBody YuLiStudioLoginUser yuLiStudioLoginUser) throws Exception
    {
        try{
            String sid=yuLiStudioLoginUser.getSessionId();
            if(!StringUtils.isEmpty(sid)){

                Map<String,String> map=(Map<String,String>)redisTemplate.opsForValue().get("sid"); //取出对象
                String phoneNumber=yuLiStudioLoginUser.getPhoneNumber();
                String code=yuLiStudioLoginUser.getCode();
                System.out.println("登录的手机号: "+phoneNumber);
                System.out.println("登录code: "+code);

                //从redis中获取保存的验证码
                String savedPhone=map.get("phoneNumber");
                String savedCode = map.get("code");
                System.out.println("从redis中取出号码: "+savedPhone);
                System.out.println("从redis中取出code: "+savedCode);

                if(!phoneNumber.equals(savedPhone)){
                    redisTemplate.delete("sid");
                    return R.error("手机号码不正确,请重新获取验证码");
                }

                //验证码验证成功
                if (code.equals(savedCode)) {

                    // 验证成功，可以进行后续操作
                    redisTemplate.delete("sid");

                    //输出用户信息到前端
//                    Students studentInfo=studentsService.selectStudentsByUserPhone(phoneNumber);
//                    if(Objects.isNull(studentInfo)){ //用户尚未注册，第一次登录注册
//                        studentInfo=new Students();
//                        studentInfo.setHeadimg(defaultHeadimg); //默认头像
//                        studentInfo.setUserphone(phoneNumber);
//                        studentInfo.setUsername(phoneNumber);
//                        studentInfo.setHeadimg("https://yulistudio.oss-cn-shenzhen.aliyuncs.com/images/bg/head.png");
//                        studentInfo.setUsersex("未知");
//                        studentInfo.setRemark("新用户注册");
//                        studentsService.insertStudents(studentInfo); //插入新注册信息
//                    }

                    //保存用户信息Redis
                    //student_+sessionId
                    //redisTemplate.opsForValue().set("student_"+sid,studentInfo);

                    //生成jwt码
                    //生成全局唯一uuid
                    Map<String,String> keys=new HashMap<String,String>();
                    keys.put("sessionid",sid);
                    String Token= jwtUtils.createToken(keys);
                    System.out.println("生成token===========>" + Token);

                    //设置token返回到客户端
                    //studentInfo.setToken(Token);

                    //return R.ok("登录成功").put("data",studentInfo);

                } else {
                    // 验证失败
                    return R.error("请输入正确验证码");
                }
            }
            return R.ok("登录成功"); //为了保持同一session会话
        }
        catch (Exception e) {
            System.out.println(e.getMessage());
            return R.error(408,"登录失败,请重新获取验证码");
        }
    }



    /**
     * 发送验证码
     */
    @PostMapping("/sendMessage")
    public R sendMessage(@RequestBody YuLiStudioLoginUser yuLiStudioLoginUser) throws Exception
    {
        Map<String,String> map=new HashMap<>();
        String phoneNumber=yuLiStudioLoginUser.getPhoneNumber();
        // 假设验证手机号成功，生成一个随机的验证码
        String verificationCode = Tools.generateCode4();

        if(!StringUtils.isEmpty(phoneNumber)) {
            AliyunSMS.SendMessage(phoneNumber,verificationCode);
            System.out.println("验证码已发送:==>" + verificationCode);
        }

        //打包
        map.put("phoneNumber",phoneNumber);
        map.put("code",verificationCode);

        try{
            //前端一定要携带sessionid回传
            String sid="";
            if(!Objects.isNull(yuLiStudioLoginUser.getSessionId())){
                sid=yuLiStudioLoginUser.getSessionId();
            }
            if(!StringUtils.isEmpty(sid)){
                System.out.println("同一个用户操作");
                System.out.println(sid);
            }else{
                //生成1个全局唯一的sessionid用于发送到客户端进行后续会话同步操作，读取redis存储信息
                sid=request.getSession().getId();
                System.out.println("当前会话id:==>"+sid);
            }

            //封装对象进Redis
            redisTemplate.opsForValue().set("sid",map);
            return R.ok("短信验证码发送成功").put("sid",sid); //为了保持同一session会话
        }
        catch (Exception e) {
            return R.error(408,"短信发送失败");
        }
    }



    //检查短信验证码过期时间
    private Boolean CheckSMSexpiredTime(HttpSession session){
        if(Objects.isNull(session.getAttribute("expiredTime"))) return false;
        Long expiredTime=(Long) session.getAttribute("expiredTime");
        Long nowTime = System.currentTimeMillis();
        System.out.println("时间戳对比"+((nowTime-expiredTime)/60000)+"分钟");
        return ((nowTime-expiredTime)/60000)>1?true:false;
    }



























} //Class End
